/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chatroom.com.clientserver;

import chatroom.com.entity.MessageModel;
import chatroom.com.entity.UserModel;
import chatroom.com.frame.AdminFrame;
import chatroom.com.util.EmailTool;
import chatroom.com.util.UserService;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import java.util.Set;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ServerThread implements Runnable {

    private String name;// 用户的名字，也是这个线程的名字
    private String sex;// 用户的性别
    private Socket socket;
    private int index = 0;
    private String ipAddress;
    BufferedReader in;
    PrintWriter out;

    /**
     * 无参构造
     */
    public ServerThread() {
    }

    public ServerThread(Socket socket, String ipAddress) throws IOException {
        this.setSocket(socket);
        this.setIpAddress(ipAddress);

        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        out = new PrintWriter(socket.getOutputStream());
//		updateList();
    }

    private void updateList() {
        // 更新用户列表（即发送当前在聊天室的用户到新来的用户列表中）
        Vector<ServerThread> clients = ChatServer.getClients();
        if (clients != null) {
            for (ServerThread st : clients) {

                int count = ChatServer.getClients().size();
                if (st.getName() != null && st.getSex() != null) {
                    out.println("oldUserList" + "&" + st.getName() + "&" + st.getSex()
                            + "&" + count + "&" + this.getIndex());
                    out.flush();
                    return;
                }
            }
        }

    }

    public void updateAdminUserList(int index) {
        Vector<ServerThread> clients = ChatServer.getClients();
        if (clients != null) {
            for (ServerThread st : clients) {
                if (st != null) {
                    if (index > this.getIndex()) {
                        st.setIndex(st.getIndex() - 1);
                    }
                }
            }
        }
    }

    @Override
    public void run() {
        boolean state = true;
        while (state) {
            try {
                String flagMsg = in.readLine();

                if (flagMsg.startsWith("updateList")) {//用户登录成功，刷新用户列表
                    UserModel user = UserModel.getUserByString(flagMsg);
                    AdminFrame.addNewUser(user, ChatServer.getClients().size());
                    updateList();
                    this.setName(user.getNick());
                    this.setSex(user.getSex());
                    this.setIndex(ChatServer.getClients().size());
                    ChatServer.sendMsgToAll("newAddUser&" + user.getNick() + "&" + user.getSex() + "&" + ChatServer.getClients().size());
                } else if (flagMsg.startsWith("login")) {//用户登录请求
                    UserModel user = UserModel.getUserByString(flagMsg);
                    boolean flag = UserService.judgeLogin(user.getUserName(),
                            user.getUserPass());
                    if (flag) {// 用户名跟密码验证成功
                        UserModel loginUser = UserService.getUserByName(user.getUserName());
                        loginUser.setUserState(Integer.parseInt(flagMsg.split("&")[9]));
                        out.println("LOGINOK&" + UserModel.userToString(loginUser));
                        out.flush();

                    } else {
                        out.println("ERROR");
                        out.flush();
                    }
                } 
                else if(flagMsg.startsWith("getpass")){//找回密码
                    String str[] = flagMsg.split("&");
                    UserModel user = UserService.getUserByNameAndEmail(str[1], str[2]);
                    if(user.getUserName()==null){
                        out.println("geterror");
                        out.flush();
                    }
                    else{
                        EmailTool.getPass(user.getEmail(), "亲爱的用户，您好，您的用户名为："+user.getUserName()+"\n.您的密码是："+user.getUserPass());
                        out.println("getok");
                        out.flush();
                    }
                }
                
                else if (flagMsg.startsWith("registername")) {//用户注册
                    String str[] = flagMsg.split("&");
                    UserModel user = UserService.getUserByName(str[1]);
                    if (user.getUserPass() == null) {
                        out.println("haveno");
                        out.flush();
                    } else {
                        out.println("have");
                        out.flush();
                    }
                } else if (flagMsg.startsWith("registernick")) {
                    String str[] = flagMsg.split("&");
                    UserModel user = UserService.getUserByNick(str[1]);
                    if (user.getUserPass() == null) {
                        out.println("haveno");
                        out.flush();
                    } else {
                        out.println("have");
                        out.flush();
                    }
                } else if (flagMsg.startsWith("register")) {
                    UserModel user = UserModel.getUserByString(flagMsg);
                    UserService.register(user);
                    out.println("registerok");
                    out.flush();
                } else if (flagMsg.equals("quit")) {//用户退出                   
                    AdminFrame.deleteOneUser(this.getIndex(), this.getName());
                    updateAdminUserList(this.getIndex());
                    ChatServer.deleteConnection(this.getSocket(), this);
                    ChatServer.sendMsgToAll("quit&" + this.getName() + "&" + " 退出了聊天室" + "&" + ChatServer.getClients().size());
                } else if (flagMsg.equals("flush")) {//刷新用户列表
                    this.updateList();
                } else if (flagMsg.startsWith("sendfile")) {//接收到客户端发来的发送文件的信号
                    String[] str = flagMsg.split("&");//flagMsg = ("sendfile&" + toName + "&" + this.myname + "&" + fd.getFile().toString() + "&" + this.toIp);
                    ChatServer.sendMsgToAll("receivefile&" + str[1] + "&" + str[2] + "&" + str[3] + "&" + str[4]);
                } else if (flagMsg.startsWith("getIp")) {
                    String[] str = flagMsg.split("&");
                    out.println("ip&" + ChatServer.getIpAddressByNick(str[1]) + "&" + str[1]);
                    out.flush();
                } else if (flagMsg.startsWith("lookUserByNick")) {//查看用户信息
                    String[] str = flagMsg.split("&");
                    UserModel loginuser = UserService.getUserByNick(str[1]);
                    if (loginuser != null) {
                        out.println("detailOfUser&" + UserModel.userToString(loginuser));
                        out.flush();
                    }
                } else if (flagMsg.startsWith("songhua")) {// son送花                    
                    ChatServer.sendMsgToAll(flagMsg);
                    String temp[] = flagMsg.split("&");
                    MessageModel mg = new MessageModel();
                    mg.setZiti("宋体");
                    mg.setDaxiao("16");
                    mg.setYanse("红色");
                    mg.setYangshi("常规");
                    mg.setFromWho(temp[1]);
                    mg.setToWho(temp[2]);
                    mg.setContent("#sh");
                    AdminFrame.insertHuaToPane(mg);//将收到的消息插入到服务器面板
                } else if (flagMsg.startsWith("usermessage")) {//发送聊天信息，一般分为公聊信息，和私聊信息
                    MessageModel msg = MessageModel.getMsgByString(flagMsg);
                    AdminFrame.insertMessageToJTextPane(msg);//将收到的消息插入到服务器面板
                    ChatServer.sendMsgToAll("liaotianxinxi&" + MessageModel.getStringByMessage(msg));
                }
            } catch (Exception e) {
                try {
                    socket.close();
                } catch (IOException ex) {
                    Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
                }
                return;
            }
        }

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getIpAddress() {
        return ipAddress;
    }

    public void setIpAddress(String ipAddress) {
        this.ipAddress = ipAddress;
    }
}
